package com.tt.payee.service.login.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tt.payee.business.AbortException;
import com.tt.payee.domain.TbRole;
import com.tt.payee.domain.TbRoleUser;
import com.tt.payee.domain.TbUser;
import com.tt.payee.domain.vo.TbUserVo;
import com.tt.payee.mapper.TbRoleUserMapper;
import com.tt.payee.mapper.TbUserMapper;
import com.tt.payee.service.login.TbUserService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Tang
 * @Description: 管理员用户
 * @date:2020-03-11 13:58
 */
@Service
@Slf4j
public class TbUserServiceImpl implements TbUserService {

    @Autowired
    TbUserMapper tbUserMapper;

    @Autowired
    TbRoleUserMapper tbRoleUserMapper;

    @Override
    public TbUser getById(Long userId) {
        TbUser user = tbUserMapper.getById(userId);
        return user;
    }

    @Override
    public TbUser getOne(TbUser tbUser) {
        TbUser user = new TbUser();
        user.setUsername(tbUser.getUsername());
        TbUser tempUser = tbUserMapper.selectOne(user);
        if(tempUser==null){
            throw new AbortException("无此用户");
        }
        if(new BCryptPasswordEncoder().matches(tbUser.getPassword(),tempUser.getPassword())){
            return tempUser;
        }
        return null;
    }

    @Override
    public PageInfo<TbUser> getList(TbUserVo tbUserVo) {

        //TbUser tbUser = new TbUser();
        //BeanUtils.copyProperties(tbUserVo, tbUser);
        PageHelper.startPage(tbUserVo.getCurrentPage(),tbUserVo.getPageSize());
        List<TbUser> list = tbUserMapper.getList(tbUserVo);
        PageInfo<TbUser> pageInfo = new PageInfo<TbUser>(list);

        return pageInfo;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int insert(TbUser tbUser) {
        //判断有没有重复的username
        TbUser tempUser = new TbUser();
        tempUser.setUsername(tbUser.getUsername());
        TbUser tbUserTemp = tbUserMapper.selectOne(tempUser);

        if (tbUserTemp != null) {
            throw new AbortException("用户名已存在");
        }

        //初始密码加密
        tbUser.setPassword(new BCryptPasswordEncoder().encode("123456"));

//        //插入管理员账号
        tbUser.setIsAdmin(0);
        tbUser.setLoginVersion(1);
        tbUser.setStatus(1);
        int result = tbUserMapper.insertSelective(tbUser);

        if (result <= 0) {
            throw new AbortException("用户添加失败");
        }

        //插入账号角色
        if(tbUser.getRoleList()==null || tbUser.getRoleList().size()<=0){
           return result;
        }

        List<TbRoleUser> roleUserList = new ArrayList<>();
        TbRoleUser roleUser = null;
        for(TbRole role:tbUser.getRoleList()){
            roleUser = new TbRoleUser();
            roleUser.setRoleId(role.getRoleId());
            roleUser.setUserId(tbUser.getUserId());
            roleUserList.add(roleUser);
        }
        for(TbRoleUser roleUser2:roleUserList){
            int num = tbRoleUserMapper.insertSelective(roleUser2);
            if(num<=0){
                throw new AbortException("用户绑定角色失败");
            }
        }

        return result;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int update(TbUser tbUser) {

        TbUser tempUser =  tbUserMapper.selectByPrimaryKey(tbUser.getUserId());
        if (tempUser == null) {
            throw new AbortException("用户不存在");
        }

        TbUser sameUser = new TbUser();
        sameUser.setUsername(tbUser.getUsername());
        sameUser =  tbUserMapper.selectOne(sameUser);
        if(sameUser!=null && !sameUser.getUserId().equals(tempUser.getUserId())){
            throw new AbortException("用户名已存在");
        }

        tempUser.setUsername(tbUser.getUsername());
        tempUser.setNickName(tbUser.getNickName());
        //插入管理员账号
        int result = tbUserMapper.updateByPrimaryKeySelective(tempUser);

        if (result <= 0) {
            throw new AbortException("用户修改失败");
        }

        //插入角色关联
        TbRoleUser tempRoleUser = new TbRoleUser();
        tempRoleUser.setUserId(tempUser.getUserId());
        tbRoleUserMapper.delete(tempRoleUser);
        if(tbUser.getRoleList()==null || tbUser.getRoleList().size()<=0){
            return result;
        }

        List<TbRoleUser> roleUserList = new ArrayList<>();
        TbRoleUser roleUser = null;
        for(TbRole role:tbUser.getRoleList()){
            roleUser = new TbRoleUser();
            roleUser.setRoleId(role.getRoleId());
            roleUser.setUserId(tbUser.getUserId());
            roleUserList.add(roleUser);
        }
        for(TbRoleUser roleUser2:roleUserList){
            int num = tbRoleUserMapper.insertSelective(roleUser2);
            if(num<=0){
                throw new AbortException("用户绑定角色失败");
            }
        }
        return result;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int deleteByIds(Long[] ids) {

        TbUser user = null;
        TbUser editUser = null;
        for(Long id:ids){
            user = tbUserMapper.selectByPrimaryKey(id);
            if(user==null){
                throw new AbortException("无此用户id："+id);
            }
            if(user.getIsAdmin()==1){
                throw new AbortException("超级管理员无法删除");
            }
            editUser = new TbUser();
            editUser.setStatus(-1);
            editUser.setUserId(user.getUserId());
            tbUserMapper.updateByPrimaryKeySelective(editUser);
        }
        return 1;
    }

    @Override
    public TbUser getByIdWithPermission(Long userId) {
        return tbUserMapper.getByIdWithPermission(userId);
    }

    @Override
    public int changeAttr(TbUser tbUser) {
        TbUser user = tbUserMapper.selectByPrimaryKey(tbUser.getUserId());
        if(user == null){
            throw new AbortException("用户id错误");
        }
        if(user.getIsAdmin()==1){
            throw new AbortException("超级管理员无法修改状态");
        }
        int result = tbUserMapper.updateByPrimaryKeySelective(tbUser);
        return result;
    }
}
